package io

import (
	"errors"

	"go.bug.st/serial"
)

type IConnectionClient interface {
	IsConnecting() bool
	AutoReconnect(async bool)
	Connect() error
	Read() ([]byte, error)
	Write(buffer []byte) error
}

func CreateTCPClient(ip string, port, timeOutMilsecond int, autoReconnect bool) (*TCPClient, error) {
	res := new(TCPClient)
	res.useAutoReconnect = autoReconnect
	res.ip = ip
	res.port = port
	res.connecting = false
	res.timeOutMilsecond = timeOutMilsecond
	if res.useAutoReconnect {
		res.AutoReconnect(false)
		return res, nil
	}
	return res, res.Connect()
}

func CreateCommClient(comName string, baudRate, dataBits, stopBits, parity, timeOutMilsecond int, autoReconnect bool) (*COMMClient, error) {
	if stopBits < 0 || stopBits > 2 {
		return nil, errors.New("stopBits参数错误")
	}
	if parity < 0 || parity > 4 {
		return nil, errors.New("parity参数错误")
	}
	if dataBits < 5 || dataBits > 8 {
		return nil, errors.New("dataBits参数错误")
	}
	res := new(COMMClient)
	res.useAutoReconnect = autoReconnect
	res.comName = comName
	res.Mode.BaudRate = baudRate
	res.Mode.DataBits = dataBits
	res.Mode.StopBits = serial.StopBits(stopBits) // stopBits
	res.Mode.Parity = serial.Parity(parity)       // parity
	res.timeOutMilsecond = timeOutMilsecond
	if res.useAutoReconnect {
		res.AutoReconnect(false)
		return res, nil
	}
	return res, res.Connect()
}
